<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Campaign;

class FeedUnit extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function method(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedunit:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'a.'.$sort;
		}

		array_push( $where, ['a.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['a.userType', '=', 2 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['a.bazaarId', '=',  $bazaarId ] );
		}

		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['a.userId', '=',  $userId ] );
		}

		$campaignId = $request->param('campaignId', '', 'trim');
		if($campaignId) {
			array_push( $where, ['a.campaignId', 'in',  $campaignId ] );
		}

		$status = $request->param('status/d', '', 'trim');
		if( $status === 0) {
			array_push( $where, ['a.status', '=',  $status ] );
		}
		if( $status === 1) {
			array_push( $where, ['a.status', '=',  $status ] );
		}
		if( $status === 2) {
			array_push( $where, ['a.status', '=',  $status ] );
		}
		
		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
		}

    $search = [];
		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $search, " s.userType = 2 ");
		array_push( $search, " s.adgroupid > 0 ");
		array_push( $search, " a.adgroupId = s.adgroupid ");
	  array_push( $search, " s.datatime BETWEEN {$time[0]} AND {$time[1]} ");
 //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $where, ['a.userid', 'in',  $authaccount ] );
			}
		}
		$query = Db::table('cfg_adgroup')
		->alias('a')
		->field('a.id, a.userId, a.bazaarId, a.status, a.maxPrice, a.campaignId, a.campaignName, a.adgroupId, a.adgroupName, a.regionName, a.regionTarget, a.ftypes, a.extend1, a.extend2, a.datatime,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->group('a.adgroupId')
		->order($sort, $order)
		->paginate($limit);

		//echo Db::getLastSql() . "\n\n\n"; 

    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
			$value['extend1'] = unserialize($value['extend1']);
			$value['ftypes'] = explode(',', $value['ftypes']);
		}

		$total = Db::table('cfg_adgroup')
		->alias('a')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
	 		IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->find();

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 2),
			'bazaar' => Bazaar::getList($request->sessInfo, 2)];
	}

	/**
	* 查询账号创意
	*
	* @param tValue
	* @return
	*/
	public function getCampaign(Request $request) {
		$userid = $request->param('userid', '', 'trim');
		if( empty($userid)) {
			return ['code'=> 0, 'campaign'=> [] ];
		}
		return ['code'=> 0, 'campaign'=> Campaign::getList($request->sessInfo, $userid)];
	}

	/**
	* 单元执行地址
	*
	* @param tValue
	* @return
	*/
	private function updateAdgroupFeed($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/feed/v1/AdgroupFeedService/updateAdgroupFeed', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	* 同步百度官方单元
	*
	* @param tValue
	* @return
	*/
	public function getCloud(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feedunit:cloud')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if( empty($userId) ) {
			return ['code'=> 403, 'msg'=> '请选择要同步的账号!'];
		}

		$obj = Expand::getUserInfo($request->sessInfo, $userId, 2);
		if(!is_object($obj)) {
			return ['code'=> 403, 'msg'=> '数据异常,请稍后重试!'];
		}

    $campaignIds = [];
    $campaign = Db::table('cfg_campaign')->field('id, campaignId')->where('userId', $obj->userid)->select()->toArray();
		if(is_array($campaign)){
			foreach( $campaign as $value) {
			  array_push($campaignIds, $value['campaignId']);
			}
		}

		if( count($campaignIds) == 0 ) {
			return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
		}

		$result = $this->getAdgroupFeed($obj, $campaignIds);
		if( $result['code'] == 403 ) {
			return json($result);
		}
		$adgroupIdArray = [];
		$campaignNameArray = Db::table('cfg_campaign')->field('campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)->select()->toArray();
    if(is_array($result['data'])) {
			foreach($result['data'] as $value) {
				array_push($adgroupIdArray, $value['adgroupFeedId']);
				$maxPrice = $value['bid'];
				if(empty($value['bid'])){
					$maxPrice = isset($value['ocpc']['ocpcBid']) ? $value['ocpc']['ocpcBid'] : 0;
				}
				$campaignName = cloud_get_array_value($campaignNameArray, $value['campaignFeedId'], 'campaignId', 'campaignName', null);
				$adgroupId = Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])->where('adgroupId', $value['adgroupFeedId'])->value('id');
				if($adgroupId) {
 					Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupFeedId'])->update([
						'datatime' => date('Y-m-d H:i:s'),
						'bazaarId' => $obj->bazaarId,
						'adgroupName' => $value['adgroupFeedName'],
						'campaignName' => $campaignName,
						'status' => $value['status'],
						'ftypes' => implode(',', $value['ftypes']),
						'extend1' => serialize($value['ocpc']),
						'extend2' => $value['bidtype'],
						'maxPrice' => $maxPrice,
					]);
				} else {
					Db::name('cfg_adgroup')->insert([
					  'companyId' => $request->sessInfo['companyId'],
						'userType' => 2,
						'userId' => $userId,
						'bazaarId' => $obj->bazaarId,
						'datatime' => date('Y-m-d H:i:s'),
						'adgroupId' => $value['adgroupFeedId'],
						'adgroupName' => $value['adgroupFeedName'],
						'campaignId' => $value['campaignFeedId'],
						'campaignName' => $campaignName,
						'status' => $value['status'],
						'ftypes' => implode(',', $value['ftypes']),
						'extend1' => serialize($value['ocpc']),
						'extend2' => $value['bidtype'],
						'maxPrice' => $maxPrice,
					]);
				}
			}
			if(count($adgroupIdArray) > 0) {
				Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)->where('userId', $userId)
					->whereNotIn('adgroupId', $adgroupIdArray)->delete();
				//echo Db::getLastSql() . "\n";
				Db::table('cfg_search')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)->where('userid', $userId)->where('adgroupid', '>', 0)
					->whereNotIn('adgroupid', $adgroupIdArray)->delete();
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	/**
	* 读取最新单元数据
	*
	* @param tValue
	* @return
	*/
	private function getAdgroupFeed($obj, $adgroupId) {
		$response = doPostRequest('https://api.baidu.com/json/feed/v1/AdgroupFeedService/getAdgroupFeed', json_encode([
			'header'=>['username'=> $obj->username, 'password'=> $obj->password, 'token'=>$obj->token],
			'body'=> [
        "ids" => $adgroupId,
        "idType" => 1,
        "adgroupFeedFields"=>[
            "adgroupFeedId",
            "campaignFeedId",
            "adgroupFeedName",
            "pause",
            "status",
            "bid",
						"producttypes",
						"ftypes",
						"bidtype",
						"ocpc",
            "atpFeedId",
            "addtime",
        ]
			]
		]));

		if(empty($response)) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		$result = json_decode ($response, true);
		if(!isset($result['header']['desc'])){
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if(!isset($result['header']['desc'])) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if($result['header']['desc'] == 'failure') {
			$tempMessage  = explode('sn:', $result['header']['failures'][0]['message']);
			return ['code'=> 403, 'msg'=> 'code: ' . $result['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] ];
		}

		if( isset($result['body']['data'])) {
			return ['code'=> 0, 'data'=> $result['body']['data'] ];
		}

		return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
	}

	/**
	 * 设置单元状态
	 *
	 * @return
	 */
	public function setPause(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:pause')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$selectId = $request->param('selectId/a', '', 'trim');
		if( count($selectId) == 0 ) {
			return ['code'=> 403, 'msg'=> '请选择要设置的单元!'];
		}
		$result = [];
		$beginTime = microtime(true);
		$pause = $request->param('pause/d', '', 'trim');
		$query = Db::table('cfg_adgroup')->field('id, userId, campaignId, adgroupId, adgroupName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $selectId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
				if(is_object($obj)) {
					$response = $this->updateAdgroupFeed(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'adgroupFeedTypes'=>[
								[
									"adgroupFeedId"=> $value['adgroupId'],
									"pause"=> $pause,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$status = 1;
						if($pause === 0) {
							$adgroupIdArr = [];
							array_push($adgroupIdArr, $value['campaignId']);
							$adgroupFeed = $this->getAdgroupFeed($obj, $adgroupIdArr);
							if( isset($adgroupFeed['data'][0]['status'])) {
								$status = $adgroupFeed['data'][0]['status'];
							}
				    }
						Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['status' => $status]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流单元报告', '设置单元状态, ' . $pause, 0, null);
						array_push($result, '['.$value['adgroupName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 批量设置计划推广地域
	 *
	 * @return
	 */
	public function updateRegionTarget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedunit:regionTarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('ids/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的单元!'];
		}

		$regionName = '';
		$regionTarget = [];
		$regionPriceFactor = [];
		$regionTargetData = $request->param('regionTarget', '', 'trim');
		$regionTargetArray = json_decode($regionTargetData);
		if(count($regionTargetArray ) > 0){
			$cityNumber = 0;
			foreach( $regionTargetArray as $value) {
				if(in_array($value->id, [ 1000, 2000, 3000, 33000, 34000, 35000, 36000])) {
					$cityNumber++;
			    $regionName = $value->label;
					array_push($regionTarget, $value->id);
					array_push($regionPriceFactor, ['regionId'=> $value->id, 'priceFactor'=>$value->priceFactor]);
				}
				foreach( $value->children as $key => $item) {
					if($key == 0 ) {
						$regionName = $item->label;
					}
					$cityNumber++;
					array_push($regionTarget, $item->id);
					array_push($regionPriceFactor, ['regionId'=> $item->id, 'priceFactor'=>$item->priceFactor]);
				}
			}
			$regionName = $regionName . '等' . $cityNumber . '个';
		}

		if( count($regionTarget) == 0 ) {
			return ['code'=>403, 'msg'=>'请至少选择一个地域!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_adgroup')->field('id, userId, adgroupId, adgroupName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
				if(is_object($obj)) {
					$response = $this->updateAdgroupFeed(json_encode([
						'header'=> ['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'adgroupFeedTypes'=>[
								[
									"adgroupFeedId"=> $value['adgroupId'],
									"atpFeedId" => 0,
									"audience"=> [
										"region" => implode (',', $regionTarget)
									]
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
							Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['regionName' => $regionName, 'regionTarget' => $regionTargetData]);
							$endTime = microtime(true);
							$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
							$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流单元报告', '设置计划推广地域' . $regionName , 0, null);
							array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['adgroupName'].'] 操作成功.</span>');
						} else {
							$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
							array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
						}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}
	
	/**
	 * 查询推广地域
	 *
	 * @return
	 */
	public function regionTarget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedunit:regionTarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'请选择要查询的计划!'];
		}
		$query = Db::table('cfg_adgroup')->field('id, regionTarget')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}
		$query['regionTarget'] = json_decode($query['regionTarget']);
		return json(['code'=>0, 'data' => $query, 'msg'=>'']);
	}
	
	/**
	 * 设置单元每日预算
	 *
	 * @return
	 */
	public function setmaxPrice(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:maxPrice')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];
		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的单元!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$maxPrice = $request->param('maxPrice', '', 'trim');
		$query = Db::table('cfg_adgroup')->field('id, userId, adgroupId, adgroupName, extend1')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$extend1 = [];
				if( $value['extend1'] ){
					$extend1 = unserialize($value['extend1']);
					if( isset($extend1['appTransId']) ) {
						$extend1['ocpcBid'] = $maxPrice;
						$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
						if(is_object($obj)) {
							$response = $this->updateAdgroupFeed(json_encode([
								'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
								'body'=> [
									'adgroupFeedTypes'=>[
										[
											"adgroupFeedId"=> $value['adgroupId'],
											"ocpc"=> $extend1
										]
									]
								]
							]));
						if($response['header']['desc'] == 'success') {
							Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['maxPrice' => $maxPrice]);
							$endTime = microtime(true);
							$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
							$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流单元报告', '设置单元出价, ' . $maxPrice . '元', 0, null);
							array_push($result, '['.$value['adgroupName'].'] 操作成功.');
						} else {
							$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
							array_push($result, '['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
						}
						}
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}
	
}
